package com.zhxh.nzpos.serialport;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidParameterException;

import szxb.test.ll.jni.test4052;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android_serialport_api.SerialPort;

import com.zhxh.nzpos.Constants;
import com.zhxh.nzpos.R;

/**
 * 串口打印父类
 * 
 * @author wangzt
 *
 */
public abstract class PrintSerialPort extends Activity {

	protected SerialPort mSerialPort;
	protected OutputStream mOutputStream;
	private InputStream mInputStream;
	private ReadThread mReadThread;
	
	private class ReadThread extends Thread {

		@Override
		public void run() {
			super.run();
			while(!isInterrupted()) {
				int size;
				try {
					byte[] buffer = new byte[64];
					if (mInputStream == null) return;
					size = mInputStream.read(buffer);
					if (size > 0) {
						onDataReceived(buffer, size);
					}
				} catch (IOException e) {
					e.printStackTrace();
					return;
				}
			}
		}
	}
	
	private void DisplayError(int resourceId) {
		AlertDialog.Builder b = new AlertDialog.Builder(this);
		b.setTitle("Error");
		b.setMessage(resourceId);
		b.setPositiveButton("OK", new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				PrintSerialPort.this.finish();
			}
		});
		b.show();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try {
			test4052.testopen();
			test4052.testioctl(1);
			mSerialPort = new SerialPort(new File(Constants.SERIAL_PATH), Constants.SERIAL_BOUNDRATE, 0);
			mOutputStream = mSerialPort.getOutputStream();
			mInputStream = mSerialPort.getInputStream();
			if (mSerialPort != null) {
				mReadThread = new ReadThread();
				mReadThread.start();
			}
		} catch (SecurityException e) {
			DisplayError(R.string.error_security);
		} catch (IOException e) {
			DisplayError(R.string.error_unknown);
		} catch (InvalidParameterException e) {
			DisplayError(R.string.error_configuration);
		}
	}
	protected abstract void onDataReceived(final byte[] buffer, final int size);
	

	@Override
	protected void onDestroy() {
		if (mSerialPort != null) {
			mSerialPort.close();
			if (mReadThread != null) {
				mReadThread.interrupt();
				mReadThread = null;
			}
		}
		mSerialPort = null;
		super.onDestroy();
	}

	
}
